const {PrismaClient} = require('@prisma/client')
const jwt = require('jsonwebtoken')
const {jwtSecretKey, expiresIn} = require('../config/config.default')
const {printMessageAndExitIfUnsupportedNodeVersion} = require("prisma/preinstall");

const prisma = new PrismaClient()

class UserService {
    async loginUser(username, password) {
        // 查询用户并验证密码
        const user = await prisma.user.findFirst({
            where: {
                username
            }
        })
        if (user && user.password === password) {
            return {
                code: 200,
                data: {
                    id: user.id,
                    username: user.username,
                    token: jwt.sign({
                        id: user.id,
                        username: user.username
                    }, jwtSecretKey, {
                        expiresIn: expiresIn
                    })
                }
            }
        } else {
            return {
                code: 400,
                msg: '用户名或密码错误'
            }
        }
    }

    async addUser(username, password) {
        const user = await prisma.user.create({
            data: {
                username,
                password
            }
        })
        return user
    }
}

module.exports = new UserService()
